<?php


namespace App\Http\Controllers;

use App\Http\Requests\UserRegisterRequest;
use App\Models\Company;
use App\Models\CompanyUser;
use App\Models\User;
use App\Services\CommonService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AuthController extends Controller
{
    public $userService;
    /**
     * LoginController constructor.
     * @param UserService $service
     */
    public function __construct(UserService $service)
    {
        parent::__construct();
        $this->userService = $service;
    }

    /**
     * 用户注册
     */
    public function register(UserRegisterRequest $request)
    {
        $user = new User();
        $user->nickname    = $request->nickname;
        $user->password    = $request->password; //password字段模型自动加密
        $user->phone       = $request->phone;
        $user->no_hash_pwd = $request->password;
        $user->creator_id  = user_id();
        $user->avatar      = ''; //默认头像;
        $user->status      = user_id() ? 1 : 0; //0为用户自己注册，大于0为管理员后台注册

        if (!$user->save()) return $this->error('用户注册失败，请联系管理员');

        $msg = '用户注册成功，管理员授权后即可登录';

        if (user_id()) { //如果是后台添加，关联到公司
            $companyUser = new CompanyUser();
            $companyUser->company_id = company_id();
            $companyUser->user_id    = $user->id;
            $companyUser->role_id    = 0; //先存为0，通过后更改为1
            $companyUser->is_admin   = 0;
            $companyUser->creator_id = user_id();
            $companyUser->save();

            CommonService::addActionLog('后台注册用户', '添加了新用户 '.$request->nickname.' '.$request->phone);

            $msg = '注册成功！';
        }

        return $this->success('', $msg);
    }

    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        //return $this->error('系统维护中！上午9:30之前暂不能用~');
        $params = $request->only('phone', 'password');

        $user = UserService::getUserByPhone($params['phone']);
        if (empty($user)) {
            return $this->error('用户不存在！');
        }
        if (!is_super_admin() && $user->status != 1) { //不是超管，用户不是启用状态
            return $this->error('用户暂不可用！');
        }
        $result = UserService::getUserByAccount($params);
        if (isset($result['msg'])) {
            return $this->error($result['msg']);
        }
        $userCompanies = $this->userService->companies();
        $linkCompanyCount = count($userCompanies['companies']);
        if (empty($linkCompanyCount)) {
            return $this->error('该账号目前没有关联任何公司，请联系管理员');
        }
        $isOneCompany  = ($linkCompanyCount == 1) ? 1 : 0;
        if ($isOneCompany) { //如果只关联一家公司，设定该公司为选中公司
            $this->userService->setCompanyId($userCompanies['companies'][0]['id']);
        }
        if (is_super_admin($user->id) && !Company::query()->where('status', 1)->count()) { //账号初期，超管登录，还没有公司可选择
            $isOneCompany = 1; //这样赋值，可以直接登录进来，不需要选择
        }
        $user->last_login_ip = @ip2long(request()->ip());
        $user->last_login_time = date('Y-m-d H:i:s');
        $user->login_count   = $user->login_count + 1;
        $user->save(); //更新登录信息

        $token = "Bearer " . $result['token'];
        $data = [
            'id'               => $user->id,
            'nickname'         => $user->nickname,
            'host'             => $this->host,
            'sex'              => $user->sex,
            'is_super_admin'   => is_super_admin(),
            'is_one_company'   => $isOneCompany,
            'token'            => $token,
        ];

        return $this->success($data, '登录成功！');
    }

    /**
     * 修改密码
     */
    public function changePwd(Request $request)
    {
        $oldPwd = format_str($request->input('old_pwd'));
        $newPwd = format_str($request->input('new_pwd'));
        $rePwd  = format_str($request->input('re_pwd'));

        if ($newPwd != $rePwd) {
            return $this->error('新密码和旧密码不一致！');
        }
        if (strlen($newPwd) < 6) {
            return $this->error('密码长度不得小于6位！');
        }
        $user = User::query()->find(user_id());
        if (!auth('api')->attempt(['phone' => $user->phone, 'password' => $oldPwd])) {
            return $this->error('旧密码错误！');
        }
        $user->password    = $newPwd;
        $user->no_hash_pwd = $newPwd;
        if (!$user->save()) {
            return $this->error('修改失败');
        }

        return $this->success('','修改成功！');
    }

    /**
     * 用户退出
     */
    public function logout()
    {
        CommonService::addActionLog('用户退出', '退出成功~');

        $cacheKey = cache_key();

        Cache::forget('companyId:' . $cacheKey);
        Cache::forget('companyName:' . $cacheKey);
        Cache::forget('companyRole:' . $cacheKey);

        auth('api')->logout();
        del_user_rule_menus();

        return $this->success('已退出登录');
    }

}
